package com.freddy.chat;

import com.freddy.chat.bean.SingleMessage;
import com.freddy.chat.event.CEventCenter;
import com.freddy.chat.event.Events;
import com.freddy.chat.event.I_CEventListener;
import com.freddy.chat.im.IMSClientBootstrap;
import com.freddy.chat.im.MessageProcessor;
import com.freddy.chat.im.MessageType;
import com.freddy.chat.utils.CThreadPoolExecutor;
import com.freddy.im.NettyServerDemo;
import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import org.junit.Test;

import java.util.UUID;

import static org.junit.Assert.assertEquals;

public class ExampleOhosTest implements I_CEventListener {
    private static final String[] EVENTS = {
            Events.CHAT_SINGLE_MESSAGE
    };

    private static final String USER_ID = "100002";
    private static final String TOKEN = "token_" + USER_ID;
    private static final String HOSTS = "[{\"host\":\"192.168.3.12\", \"port\":8855}]";

    @Test
    public void testBundleName() {
        final String actualBundleName = AbilityDelegatorRegistry.getArguments().getTestBundleName();
        assertEquals("com.freddy.chat", actualBundleName);

        CThreadPoolExecutor.runInBackground(NettyServerDemo::startServer);

        IMSClientBootstrap.getInstance().init(USER_ID, TOKEN, HOSTS, 1);

        CEventCenter.registerEventListener(this, EVENTS);

        sendMsg();
    }

    private void sendMsg() {
        SingleMessage message = new SingleMessage();
        message.setMsgId(UUID.randomUUID().toString());
        message.setMsgType(MessageType.SINGLE_CHAT.getMsgType());
        message.setMsgContentType(MessageType.MessageContentType.TEXT.getMsgContentType());
        message.setFromId(USER_ID);
        message.setToId("100001");
        message.setTimestamp(System.currentTimeMillis());

        MessageProcessor.getInstance().sendMsg(message);
    }

    @Override
    public void onCEvent(String topic, int msgCode, int resultCode, Object obj) {
        if (Events.CHAT_SINGLE_MESSAGE.equals(topic)) {
            final SingleMessage message = (SingleMessage) obj;
            System.out.println("message.getContent() = " + message.getContent());
        }
    }
}